<template>
  <van-nav-bar title="编辑地址" left-text="" left-arrow @click-left="goBack" />
  <van-address-edit
  :area-list="areaList"
  :address-info="info"
  show-delete
  show-set-default
  @save="onSave"
  @delete="onDelete"
/>
</template>

<script setup>
import { areaList } from '@vant/area-data';
const goBack = () => { proxy.$router.go(-1) }
const { proxy } = getCurrentInstance()
const LoginUser = reactive(proxy.$cookies.get("LoginUser"))
const addressid = ref(proxy.$route.query.addressid ?? 0)
const info=ref()

// 挂载前加载出数据
onBeforeMount(()=>{
  getAddressData()
})
const getAddressData = async ()=>{
  let result=await Api.EditInfo({addressid:addressid.value})
  if (result.code == 1) {
    const item =result.data
    info.value={
          id: item.id,
          name: item.consignee,
          tel: item.mobile,
          addressDetail: item.address,
          areaCode: item.district,
          isDefault: item.status == '1' ? true : false,
    }
  }
}

// 编辑地址
const onSave = async (val)=>{
  let data = {
        busid: LoginUser.id,
        addressid: addressid.value,
        consignee: val.name,
        code: val.areaCode,
        address: val.addressDetail,
        mobile: val.tel,
        status: val.isDefault == true ? '1' : '0',
  }

  let result=await Api.AddressEdit(data)
  if (result.code == 1) {
    showSuccessToast({
            message: result.msg,
            onClose: function() {
              goBack()
            }
        });
  }
}

// 删除地址
const onDelete = async () => {
    let data = {
      deleid: addressid.value
    }
    let result = await Api.Del(data)
    if (result.code == 1) {
        showSuccessToast({
            message: result.msg,
            onClose: function() {
              goBack()
            }
        });
    } else {
        showFailToast(result.msg);
    }
};
</script>